package com.bill.common.business.dao;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.bill.common.business.dto.SellQueryDTO;
import com.bill.common.business.entity.Sell;
import com.sinba.common.dao.BaseDAOImplHibernate;
import com.sinba.common.dto.PageDTO;
import com.sinba.common.util.StringUtils;

public class SellDAO extends BaseDAOImplHibernate<Sell> implements ISellDAO {

	public PageDTO findSellPage(SellQueryDTO queryDTO, String sord, String sidx) {
		// TODO Auto-generated method stub
		final DetachedCriteria dc = DetachedCriteria.forClass(Sell.class);
		
		//买入会员
		if(StringUtils.hasText(queryDTO.getSellUser())){
			dc.add(Restrictions.eq("sellUser", queryDTO.getSellUser()));
		}
		
		//状态
		if(queryDTO.getStatus()!=null){
			dc.add(Restrictions.eq("status", queryDTO.getStatus()));
		}
		//多个状态
		if(queryDTO.getMultipleStatus()!=null && queryDTO.getMultipleStatus().length>0){
			dc.add(Restrictions.in("status", queryDTO.getMultipleStatus()));
		}
		
		//未匹配完
		if(queryDTO.isNotEnd()){
			dc.add(Restrictions.gt("surplusMoney", 0L));
		}
		
		//买入ID
		if(queryDTO.getBuyId()!=null && queryDTO.getBuyId()>0){
			dc.createAlias("buy", "buy");
			dc.add(Restrictions.eq("buy.id", queryDTO.getBuyId()));
		}
		//买入会员
		if(StringUtils.hasText(queryDTO.getBuyUser())){
			dc.createAlias("buyUser", "buyUser");
			dc.add(Restrictions.eq("buyUser.loginName", queryDTO.getBuyUser()));
		}		
		
		//快捷支付
		if("ShortcutPay".equals(queryDTO.getShortcutPay())){
			dc.add(Restrictions.eq("remark", "快捷充值"));
		}else if("ALL".equals(queryDTO.getShortcutPay())){
			
		}else{
			dc.add(Restrictions.or(Restrictions.isNull("remark"), Restrictions.ne("remark", "快捷充值")));
		}
		
		
		//正在挂出
		if("MatchIng".equals(queryDTO.getSearchType())){
			dc.add(Restrictions.gt("surplusMoney", 0L));
			dc.addOrder(Order.asc("sellPrice"));
			dc.addOrder(Order.desc("priority"));
			dc.addOrder(Order.asc("createTime"));
		}else if("Split".equals(queryDTO.getSearchType())){//需要拆分的记录
			dc.add(Restrictions.gt("sellPrice", 0.2D));
			dc.addOrder(Order.asc("createTime"));
		}else{
			if ( ( sord != null ) && ! sord.equals( "" ) && ( sidx != null ) && ! sidx.equals( "" ) )
	        {
	            if ( sord.equals( "desc" ) )
	            {
	                dc.addOrder( Order.desc( sidx ) );
	            } else{
	                dc.addOrder( Order.asc( sidx ) );
	            }
	        }
		}
		
		return super.findPageByCriteria( dc,queryDTO.getStart(  ),queryDTO.getLimit(  ) );
	}
	
	
	public Sell findTop1SellOrder(){
		Sell sell = null;
		final DetachedCriteria dc = DetachedCriteria.forClass(Sell.class);
		dc.add(Restrictions.in("status",new Integer[]{0,1}));//状态为 排队中和匹配成功的
		dc.add(Restrictions.gt("surplusMoney", 0L));
		/*dc.createAlias("user", "user");
		dc.add(Restrictions.or(Restrictions.isNull("user.userStatus"), Restrictions.eq("user.userStatus", "0")));*/
		
		//排队6天后的订单
		/*Calendar timeCl = new GregorianCalendar(  );
		timeCl.setTime( new Date(  ) );
		timeCl.add(Calendar.DAY_OF_MONTH, -6);
		timeCl.set( Calendar.HOUR_OF_DAY, 23 );
		timeCl.set( Calendar.MINUTE, 59 );
		timeCl.set( Calendar.SECOND, 59 );
		dc.add(Restrictions.le("createTime", timeCl.getTime()));*/
		dc.addOrder(Order.asc("sellPrice"));
		dc.addOrder(Order.desc("priority"));
		dc.addOrder(Order.asc("createTime"));
		
		
		PageDTO pageDTO = super.findPageByCriteria( dc,0,10);
		if(pageDTO.getTotalSize()>0){
			sell = (Sell)pageDTO.getData().get(0);
		}
		return sell;
	}
	
	/**
	 * 今天全部卖出
	 * @return
	 */
	public List<Object> todayAllSell(){
		String hql = "select sum(sellMoney-surplusMoney) as allSell from Sell where year(matchTime)=year(now()) and month(matchTime)=month(now()) and day(matchTime)=day(now())";
		return super.getHibernateTemplate().find(hql);
		
	}
	
	/**
	 * 上一天的收盘价
	 * @return
	 */
	public List<Object> closingPrice(){
		Calendar ct = new GregorianCalendar(  );
		ct.setTime( new Date(  ) );
		ct.set( Calendar.DAY_OF_MONTH, 1 );
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String hql = "select sellPrice from Sell where matchTime is not null and  year(matchTime)=year('"+sdf.format(ct.getTime())+"') and month(matchTime)=month('"+sdf.format(ct.getTime())+"') and day(matchTime)=day('"+sdf.format(ct.getTime())+"')  order by  matchTime desc limit 0,1";
		return super.getHibernateTemplate().find(hql);
	}
	
	/**
	 * 卖出价格小于0.2并且未交易结束的所有股数
	 * @return
	 */
	public List<Object[]> lt2AllSell(){
		String hql = "select sum(surplusMoney) as surp1,sum(surplusMoney*sellPrice) as surp2 from Sell where sellPrice < 0.2 and status in (0,1)";
		return super.getHibernateTemplate().find(hql);
	}
	
	public Long allSurplusMoney(){
		String hql = "select sum(surplusMoney) as surp1 from Sell";
		List<Object> lists = super.getHibernateTemplate().find(hql);
		Long result1 = 0L;
		try {
			for(Object obj : lists){
				result1 = (Long)obj;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		if(result1==null){
			result1 = 0L;
		}
		return result1;
		
	}
	
}
